<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>key的原理</title>
    <script src="../js/vue.js"></script>
</head>

<body>
<div id="root">

    <!-- 

        key的作用：
        dom节点的唯一标识，用于diff算法比较
        1、index做key，倒添加，现有节点key变化，内容需要重新渲染；
        2、id做key，倒添加，可复用原页面元素。

     -->
    <!-- 遍历数组 -->
    <h2>人员列表</h2>
    <button @click.once="add">添加一个人员</button> 
    <ul>
        <li v-for="(p,index) in persons" :key="index">
            {{p.name}}-{{p.age}}
            <input type="text" v-bind:id="p.id">
        </li>
    </ul>
</div>
</body>
<script>
    Vue.config.productionTip = false

    new Vue({
        el: '#root',
        data: {
            persons: [
                {id: '001', name: 'natsu', age:18},
                {id: '002', name: 'lucy', age:17}, 
                {id: '003', name: 'grey', age:16}
            ],
            str: 'hello',
        },
        methods: {
            add() {
                this.persons.unshift({id: '004', name: 'aiersa', age:19})
            }
        }
    })
</script>

</html>